<?php

// @formatter:off
/**
 * @file t.items.tag2group.php
 * @author Alejandro Dario Simi
 * @date $Date: 2014-05-04 01:33:52 +0000 (Sun, 04 May 2014) $
 *
 * $Id: t.items.tag2group.php 111 2014-05-04 01:33:52Z daemonraco@gmail.com $
 * $URL: http://wcomix.googlecode.com/svn/trunk/tools/t.items.tag2group.php $
 */
$wcToolScripts["item.tag2group"] = array(
	"name" => "Tag To Group",
	"description" => "Moves comics and images of certain tag to another group",
	"class" => "WCToolTag2Group",
	"url" => "http://code.google.com/p/wcomix/",
	"enabled" => true
);

// @formatter:on

class WCToolTag2Group extends WCTool {
	/**
	 * @var PDOStatement
	 */
	protected $_insertComic = false;
	/**
	 * @var PDOStatement
	 */
	protected $_insertImage = false;
	//
	// Public methods.
	public function run($spacer = "") {
		global $wcDefaults;
		global $wcOptions;
		global $wcUser;

		if(!$wcUser) {
			$wcUser = new WCUser();
			$wcUser->load(WC_USER_ROOT_ID);
		}

		//
		// Checking that Read Only Mode is not activated.
		if(!$wcDefaults["read-only"]) {
			if($wcOptions->activated("Tag") && $wcOptions->activated("Group")) {
				$group = WCGroupsHolder::I()->item($wcOptions->value("Group"));
				$tag = WCTagsHolder::I()->item($wcOptions->value("Tag"));

				if($group && $tag && $group->ok() && $tag->ok() && $tag->group != $group->id()) {
					$this->move($tag, $group, $spacer);
				} elseif(!$group || !$group->ok()) {
					echo $spacer.WCColorText::ShellRed("Failed").": Specified group is invalid.\n";
				} elseif(!$tag || !$tag->ok()) {
					echo $spacer.WCColorText::ShellRed("Failed").": Specified tag is invalid.\n";
				} elseif($tag->group == $group->id()) {
					echo $spacer.WCColorText::ShellRed("Failed").": Specified tag belong to the specified group.\n";
				}
			} elseif(!$wcOptions->activated("Tag")) {
				echo $spacer.WCColorText::ShellRed("Failed").": No tag id specified.\n";
			} elseif(!$wcOptions->activated("Group")) {
				echo $spacer.WCColorText::ShellRed("Failed").": No group id specified.\n";
			} else {
				$this->showHelp($spacer);
			}
		} else {
			echo $spacer.WCColorText::ShellYellow("ReadOnlyMode activated.\n");
		}
	}
	public function showHelp($spacer = "") {
		echo "{$spacer}Options:\n";
		echo "{$spacer}\t-g group-id, --group group-id\n";
		echo "{$spacer}\t\t@TODO\n\n";
		echo "{$spacer}\t-t tag-id, --tag tag-id\n";
		echo "{$spacer}\t\t@TODO\n\n";
	}
	//
	// Protected methods.
	protected function loadOptions() {
		if(!$this->_optionsLoaded) {
			global $wcOptions;

			if($wcOptions->addValueOption("Group")) {
				$wcOptions->addOptionTrigger("Group", "g");
				$wcOptions->addOptionTrigger("Group", "l");
			}
			if($wcOptions->addValueOption("Tag")) {
				$wcOptions->addOptionTrigger("Tag", "t");
				$wcOptions->addOptionTrigger("Tag", "tag");
			}

			$wcOptions->check();

			$this->_optionsLoaded = true;
		}
	}
	protected function move(WCTag &$tag, WCGroup &$group, $spacer) {
		/**
		 * @var WCTagsHolder
		 */
		$tagsHolder = WCTagsHolder::I();
		$groupRoot = WCDirectoriesHolder::I()->itemByNameInGroup("/", $group);
		$groupRoot = array_shift($groupRoot);

		$tagsToCreate = array();
		//
		// Loading items' tag names.
		// @{
		foreach($tag->comicsFull() as $comic) {
			foreach($tagsHolder->tagsOfComic($comic) as $comicTag) {
				$tagsToCreate[] = $comicTag->name();
			}
		}
		foreach($tag->imagesFull() as $image) {
			foreach($tagsHolder->tagsOfImage($image) as $comicTag) {
				$tagsToCreate[] = $comicTag->name();
			}
		}
		$tagsToCreate = array_unique($tagsToCreate);
		// @}
		//
		// Filtering and creating tags.
		echo "{$spacer}Checking Tags:\n";
		foreach($tagsToCreate as $name) {
			$newTag = $tagsHolder->itemByNameInGroup($name, $group);
			if(!$newTag) {
				echo "{$spacer}\tCreating '{$name}': ";
				$newTag = $tagsHolder->createInGroup($name, $group);
				if($newTag && $newTag->ok()) {
					echo WCColorText::ShellGreen("Done\n");
				} else {
					echo WCColorText::ShellRed("Failed\n");
				}
			}
		}
		//
		// Statements
		// @{
		$stmtId = __CLASS__."::".__FUNCTION__."[insert-comic]";
		$query = "insert\n";
		$query .= "        into {$this->_dbprefix}comics (\n";
		$query .= "                cmc_group, cmc_directory, cmc_name, cmc_size)\n";
		$query .= "        values (:group, :directory, :comic, :size)\n";
		$query .= "        on duplicate key\n";
		$query .= "                update  cmc_checked = 'Y',\n";
		$query .= "                        cmc_lost    = 'N'\n";
		$this->_insertComic = $this->_db->prepare($stmtId, $query);

		$stmtId = __CLASS__."::".__FUNCTION__."[insert-image]";
		$query = "insert\n";
		$query .= "        into {$this->_dbprefix}images (\n";
		$query .= "                img_group, img_directory, img_name, img_size)\n";
		$query .= "        values (:group, :directory, :image, :size)\n";
		$query .= "        on duplicate key\n";
		$query .= "                update  img_checked = 'Y',\n";
		$query .= "                        img_lost    = 'N'\n";
		$this->_insertImage = $this->_db->prepare($stmtId, $query);
		// @}
		//
		// Migrating items.
		// @{
		$tagExceptions = array($tag->name());
		echo "{$spacer}Moving comics:\n";
		foreach($tag->comicsFull() as $comic) {
			echo "{$spacer}\tMoving '{$comic}': ";
			if($this->moveComic($comic, $group, $groupRoot, $tagExceptions)) {
				echo WCColorText::ShellGreen("Done\n");
			} else {
				echo WCColorText::ShellRed("Failed\n");
			}
		}
		echo "{$spacer}Moving images:\n";
		foreach($tag->imagesFull() as $image) {
			echo "{$spacer}\tMoving '{$image}': ";
			if($this->moveImage($image, $group, $groupRoot, $tagExceptions)) {
				echo WCColorText::ShellGreen("Done\n");
			} else {
				echo WCColorText::ShellRed("Failed\n");
			}
		}
		// @}
	}
	protected function moveComic(WCComic &$comic, WCGroup &$group, WCDirectory &$root, $tagExceptions) {
		$moved = false;

		/**
		 * @var WCTagsHolder
		 */
		$tagsHolder = WCTagsHolder::I();

		$params = array(
			":group" => $group->id(),
			":directory" => $root->id(),
			":comic" => $comic->name(),
			":size" => $comic->size
		);

		if($this->_insertComic->execute($params)) {
			WCComicsHolder::I()->resetCache();
			$newComic = false;
			foreach(WCComicsHolder::I()->itemByNameInGroup($comic->name(), $group) as $auxComic) {
				if($auxComic->directory == $root->id()) {
					$newComic = $auxComic;
					break;
				}
			}

			if($newComic) {
				$fromPath = WCSanitizer::SystemPath("{$comic->directory()->fullPath()}/{$comic->name}");
				$toPath = WCSanitizer::SystemPath("{$root->fullPath()}/{$comic->name()}");
				rename($fromPath, $toPath);
				if(!is_file($fromPath) && is_file($toPath)) {
					foreach($tagsHolder->tagsOfComic($comic) as $tag) {
						if(!in_array($tag->name(), $tagExceptions)) {
							$newTag = array_shift($tagsHolder->itemByNameInGroup($tag->name(), $group));
							$newTag->addComic($newComic);
						}
					}
					$comic->remove();
					$moved = true;
				}
			}
		}

		return $moved;
	}
	protected function moveImage(WCImage &$image, WCGroup &$group, WCDirectory &$root, $tagExceptions) {
		$moved = false;

		/**
		 * @var WCTagsHolder
		 */
		$tagsHolder = WCTagsHolder::I();

		$params = array(
			":group" => $group->id(),
			":directory" => $root->id(),
			":image" => $image->name(),
			":size" => $image->size
		);

		if($this->_insertImage->execute($params)) {
			WCImagesHolder::I()->resetCache();
			$newImage = false;
			foreach(WCImagesHolder::I()->itemByNameInGroup($image->name(), $group) as $auxImage) {
				if($auxImage->directory == $root->id()) {
					$newImage = $auxImage;
					break;
				}
			}

			if($newImage) {
				$fromPath = WCSanitizer::SystemPath("{$image->directory()->fullPath()}/{$image->name}");
				$toPath = WCSanitizer::SystemPath("{$root->fullPath()}/{$image->name()}");
				rename($fromPath, $toPath);
				if(!is_file($fromPath) && is_file($toPath)) {
					foreach($tagsHolder->tagsOfImage($image) as $tag) {
						if(!in_array($tag->name(), $tagExceptions)) {
							$newTag = array_shift($tagsHolder->itemByNameInGroup($tag->name(), $group));
							$newTag->addImage($newImage);
						}
					}
					$image->remove();
					$moved = true;
				}
			}
		}

		return $moved;
	}
}

?>